package com.sunrise.gateway.web.servlet;

import com.sunrise.gateway.commons.CommonUtils;
import com.dap.utils.SpringUtils;
import com.sunrise.gateway.web.core.StringInputBodyPostRequestEngine;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class NotifyWechatPayServlet extends ServletBase {
    private static final String STATUS_SUCCESS = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private static final String STATUS_FAIL = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[INVALID PARAMETER OR FAIL TRADE]]></return_msg></xml>";

    private StringInputBodyPostRequestEngine engine;

    @Override
    public void init() throws ServletException {
        engine = SpringUtils.getBean(StringInputBodyPostRequestEngine.class);
        super.init();
    }

    @Override
    protected void doMyGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        execute(req, resp);
    }
    @Override
    protected void doMyPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        execute(req, resp);
    }


    private void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String resultStr;
        try {
            engine.execute(req, null, "WechatPayCallback");
            resultStr = STATUS_SUCCESS;
        } catch (Exception e) {
            LOGGER.info("", e);
            resultStr = STATUS_FAIL;
        }

        CommonUtils.writeStrIntoResponse(resultStr, resp);
    }

}
